using System.Web.Mvc;
using GoldenBicycleCompany.Core;
using SharpArch.Core.PersistenceSupport;
using SharpArch.Core.DomainModel;
using System.Collections.Generic;
using System;
using SharpArch.Web.NHibernate;
using NHibernate.Validator.Engine;
using System.Text;
using SharpArch.Web.CommonValidator;
using SharpArch.Core;

namespace GoldenBicycleCompany.Web.Controllers
{
    [HandleError]
    public class CustomersController : Controller
    {
        public CustomersController(IRepository<Customer> customerRepository) {
            Check.Require(customerRepository != null, "customerRepository may not be null");

            this.customerRepository = customerRepository;
        }

        [Transaction]
        public ActionResult Index() {
            IList<Customer> customers = customerRepository.GetAll();
            return View(customers);
        }

        [Transaction]
        public ActionResult Show(int id) {
            Customer customer = customerRepository.Get(id);
            return View(customer);
        }

        public ActionResult Create() {
            CustomerFormViewModel viewModel = CustomerFormViewModel.CreateCustomerFormViewModel();
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Customer customer) {
            if (ViewData.ModelState.IsValid && customer.IsValid()) {
                customerRepository.SaveOrUpdate(customer);

                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The customer was successfully created.";
                return RedirectToAction("Index");
            }

            CustomerFormViewModel viewModel = CustomerFormViewModel.CreateCustomerFormViewModel();
            viewModel.Customer = customer;
            return View(viewModel);
        }

        [Transaction]
        public ActionResult Edit(int id) {
            CustomerFormViewModel viewModel = CustomerFormViewModel.CreateCustomerFormViewModel();
            viewModel.Customer = customerRepository.Get(id);
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Customer customer) {
            Customer customerToUpdate = customerRepository.Get(customer.Id);
            TransferFormValuesTo(customerToUpdate, customer);

            if (ViewData.ModelState.IsValid && customer.IsValid()) {
                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The customer was successfully updated.";
                return RedirectToAction("Index");
            }
            else {
                customerRepository.DbContext.RollbackTransaction();

				CustomerFormViewModel viewModel = CustomerFormViewModel.CreateCustomerFormViewModel();
				viewModel.Customer = customer;
				return View(viewModel);
            }
        }

        private void TransferFormValuesTo(Customer customerToUpdate, Customer customerFromForm) {
			customerToUpdate.ValidLicenseNumber = customerFromForm.ValidLicenseNumber;
			customerToUpdate.FirstName = customerFromForm.FirstName;
			customerToUpdate.MiddleName = customerFromForm.MiddleName;
			customerToUpdate.LastName = customerFromForm.LastName;
			customerToUpdate.BirthDate = customerFromForm.BirthDate;
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id) {
            string resultMessage = "The customer was successfully deleted.";
            Customer customerToDelete = customerRepository.Get(id);

            if (customerToDelete != null) {
                customerRepository.Delete(customerToDelete);

                try {
                    customerRepository.DbContext.CommitChanges();
                }
                catch {
                    resultMessage = "A problem was encountered preventing the customer from being deleted. " +
						"Another item likely depends on this customer.";
                    customerRepository.DbContext.RollbackTransaction();
                }
            }
            else {
                resultMessage = "The customer could not be found for deletion. It may already have been deleted.";
            }

            TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = resultMessage;
            return RedirectToAction("Index");
        }

		/// <summary>
		/// Holds data to be passed to the Customer form for creates and edits
		/// </summary>
        public class CustomerFormViewModel
        {
            private CustomerFormViewModel() { }

			/// <summary>
			/// Creation method for creating the view model. Services may be passed to the creation 
			/// method to instantiate items such as lists for drop down boxes.
			/// </summary>
            public static CustomerFormViewModel CreateCustomerFormViewModel() {
                CustomerFormViewModel viewModel = new CustomerFormViewModel();
                
                return viewModel;
            }

            public Customer Customer { get; internal set; }
        }

        private readonly IRepository<Customer> customerRepository;
    }
}
